import java.util.Arrays;

// 定义二叉树节点类
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder.length == 0) {
            return null;
        }

        TreeNode root = new TreeNode(postorder[postorder.length - 1]);

        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == root.val) {
                int[] in_left = Arrays.copyOfRange(inorder, 0, i);
                int[] post_left = Arrays.copyOfRange(postorder, 0, i);

                int[] in_right = Arrays.copyOfRange(inorder, i + 1, inorder.length);
                int[] post_right = Arrays.copyOfRange(postorder, i, postorder.length - 1);

                root.left = buildTree(in_left, post_left);
                root.right = buildTree(in_right, post_right);

                break;
            }
        }

        return root;
    }

    // 主方法，用于测试
    public static void main(String[] args) {
        Solution solution = new Solution();

        // 示例输入：中序和后序遍历数组
        int[] inorder = {9,3,15,20,7};
        int[] postorder = {9,15,7,20,3};

        // 构建二叉树
        TreeNode root = solution.buildTree(inorder, postorder);

        // 验证结果（简单打印根节点和部分子节点）
        System.out.println("根节点值: " + root.val);
        if (root.left != null) {
            System.out.println("左子节点值: " + root.left.val);
        }
        if (root.right != null) {
            System.out.println("右子节点值: " + root.right.val);
        }

        // 更完整的验证可以通过遍历整棵树来完成
    }
}